package net.lbh.baidumapdemo;

import net.lbh.baidumap.BaiduMapAgent;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;

/**
 * 此demo用来展示如何进行地理编码搜索（用地址检索坐标）、反地理编码搜索（用坐标检索地址）
 */
public class GeoCoderDemo extends Activity implements
		OnGetGeoCoderResultListener {
	GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用
	BaiduMap mBaiduMap = null;
	MapView mMapView = null;
	
	
	EditText lat;
	EditText lon;
	
	BaiduMapAgent mMapAgent;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_geocoder);
		CharSequence titleLable = "地理编码功能";
		setTitle(titleLable);

		// 地图初始化
		mMapView = (MapView) findViewById(R.id.bmapView);
		mMapAgent = new BaiduMapAgent(mMapView);
		lat = (EditText) findViewById(R.id.lat);
		lon = (EditText) findViewById(R.id.lon);
		
		mBaiduMap = mMapView.getMap();
		// 初始化搜索模块，注册事件监听
		mSearch = GeoCoder.newInstance();
		mSearch.setOnGetGeoCodeResultListener(this);
		
		initLocation();
	}
	
	boolean isFirLoca = true;
	
	void initLocation(){
		mMapAgent.startLocation(new BDLocationListener() {
			
			@Override
			public void onReceiveLocation(BDLocation location) {

				if (location == null || mMapView == null)
					return;
				
				mMapAgent.setMyLocationData(location);
				
				
				if (isFirLoca) {
					isFirLoca = false;
					mMapAgent.movePositionToCenter(location);
					mMapAgent.setMapViewZoomTo(18.5f);
					
					lat.setText("");
					lon.setText("");
					lat.setText(String.valueOf(location.getLatitude()));
					lon.setText(String.valueOf(location.getLongitude()));
				}
				
			}
		});
		
		mMapAgent.setOnMapViewClick(new OnMapClickListener() {
			
			@Override
			public boolean onMapPoiClick(MapPoi arg0) {
				if (arg0 !=null) {
					Toast.makeText(GeoCoderDemo.this, arg0.getName(), 0).show();
					
					lat.setText("");
					lon.setText("");
					lat.setText(String.valueOf(arg0.getPosition().latitude));
					lon.setText(String.valueOf(arg0.getPosition().longitude));
				}
				return false;
			}
			
			@Override
			public void onMapClick(LatLng arg0) {
				if (arg0 == null) {
					return;
				}
				String strInfo = String.format("纬度：%f 经度：%f",
						arg0.latitude, arg0.longitude);
				Toast.makeText(GeoCoderDemo.this, strInfo, Toast.LENGTH_LONG).show();
						
				lat.setText("");
				lon.setText("");
				lat.setText(String.valueOf(arg0.latitude));
				lon.setText(String.valueOf(arg0.longitude));
			}
		});
	}

	/**
	 * 发起搜索
	 * 
	 * @param v
	 */
	public void SearchButtonProcess(View v) {
		if (v.getId() == R.id.reversegeocode) {
			
			LatLng ptCenter = new LatLng((Float.valueOf(lat.getText()
					.toString())), (Float.valueOf(lon.getText().toString())));
			// 反Geo搜索
//			mSearch.reverseGeoCode(new ReverseGeoCodeOption()
//					.location(ptCenter));
			
			mMapAgent.deCode(ptCenter, this);
			
		} else if (v.getId() == R.id.geocode) {
			EditText editCity = (EditText) findViewById(R.id.city);
			EditText editGeoCodeKey = (EditText) findViewById(R.id.geocodekey);
			// Geo搜索
//			mSearch.geocode(new GeoCodeOption().city(
//					editCity.getText().toString()).address(
//					editGeoCodeKey.getText().toString()));
			mMapAgent.enCode(editCity.getText().toString(), editGeoCodeKey.getText().toString(), this);
//			mMapAgent.enCode(editCity.getText().toString(), editGeoCodeKey.getText().toString(), new OnGetGeoCoderResultListener() {
//				
//				@Override
//				public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
//					
//				}
//				
//				@Override
//				public void onGetGeoCodeResult(GeoCodeResult result) {
//					
//					if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
//						Toast.makeText(GeoCoderDemo.this, "抱歉，未能找到结果", Toast.LENGTH_LONG)
//								.show();
//						return;
//					}
//					mMapAgent.clear();
//					mMapAgent.addMarker(result.getLocation(), R.drawable.icon_marka);
//					mMapAgent.movePositionToCenter(result.getLocation());
//					
//					String strInfo = String.format("纬度：%f 经度：%f",
//							result.getLocation().latitude, result.getLocation().longitude);
//					Toast.makeText(GeoCoderDemo.this, strInfo, Toast.LENGTH_LONG).show();
//				}
//			});
		}
	}

	@Override
	protected void onPause() {
		mMapAgent.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapAgent.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		mMapAgent.onDestroy();
		super.onDestroy();
	}

	@Override
	public void onGetGeoCodeResult(GeoCodeResult result) {
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(GeoCoderDemo.this, "抱歉，未能找到结果", Toast.LENGTH_LONG)
					.show();
			return;
		}
		mBaiduMap.clear();
		mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
				.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.icon_marka)));
		mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result
				.getLocation()));
		String strInfo = String.format("国测 纬度：%f 经度：%f",BaiduMapAgent.convertBd09llToGcj02(result.getLocation()).getLatitude(), BaiduMapAgent.convertBd09llToGcj02(result.getLocation()).getLongitude());
		Toast.makeText(GeoCoderDemo.this, strInfo, Toast.LENGTH_LONG).show();
	}

	@Override
	public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(GeoCoderDemo.this, "抱歉，未能找到结果", Toast.LENGTH_LONG)
					.show();
			return;
		}
		mBaiduMap.clear();
		mMapAgent.addMarker(result.getLocation(), R.drawable.icon_marka);
		mMapAgent.movePositionToCenter(result.getLocation());
//		mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
//				.icon(BitmapDescriptorFactory
//						.fromResource(R.drawable.icon_marka)));
//		mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result.getLocation()));
		Toast.makeText(GeoCoderDemo.this, result.getAddress(),
				Toast.LENGTH_LONG).show();
		
	}

}
